import json
import re

from django import http
from django.http import HttpResponse, response
from django.shortcuts import render

# Create your views here.
from django.views import View
from addAddress.models import Address

# def addAddress(request):
#     json_dict = json.loads(request.body.decode())
#     print(json_dict)
#     consignee = json_dict.get('consignee')
#     mobile = json_dict.get('mobile')
#     address = json_dict.get('address')
#     transportDay = json_dict.get('transportDay')
#     print(consignee, mobile, address, transportDay)
#     return HttpResponse("添加成功")


class CreateAddressView(View):
    """新增地址"""

    def get(self, request):
        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        addres = Address.objects.all()
        lists = []
        for address in addres:
            # print(i.id)
            address_dict = {
                "id": address.id,
                "consignee": address.receiver,
                "mobile": address.mobile,
                "address": address.place,
                "transportDay": address.Receiving_dates,
            }
            lists.append(address_dict)
        # # 响应保存结果
        # return http.JsonResponse({'errmsg': '新增地址成功', 'success': '操作成功'})
        return http.JsonResponse({'errmsg': '新增地址成功', 'success': '操作成功', 'item': lists})

    def post(self, request):
        """实现新增地址逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        print(json_dict)
        # 获取收货人姓名
        receiver = json_dict.get('consignee')
        # 获取收货人手机号
        mobile = json_dict.get('mobile')
        # 获取收货人详细地址
        place = json_dict.get('address')
        # 获取收货人收货时间
        Receiving_dates = json_dict.get('transportDay')
        print(receiver, mobile, place, Receiving_dates)

        # 校验参数
        if not all([receiver, mobile, place, Receiving_dates]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')

        # 保存地址信息
        address = Address.objects.create(
            receiver=receiver,
            mobile=mobile,
            place=place,
            Receiving_dates=Receiving_dates
        )

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "consignee": address.receiver,
            "mobile": address.mobile,
            "address": address.place,
            "transportDay": address.Receiving_dates,
        }

        # # 响应保存结果
        return http.JsonResponse({'errmsg': '新增地址成功', 'success': '操作成功', 'item': address_dict})


class Deladdress(View):
    """删除地址"""

    def get(self, request):
        addressId = request.GET.get("addressId")
        print(addressId)
        Address.objects.filter(id=addressId).delete()

        return http.JsonResponse({'errmsg': '删除地址成功', 'success': '操作成功', 'item': 1})